package whf.framework.web.tag;

import javax.servlet.jsp.JspException;

import whf.framework.web.tag.ext.TagStructureException;

/**
 * @author wanghaifeng
 * 
 */
public class SetPropertyTag extends HtmlTag {
	private static final long serialVersionUID = 899149338534L;

	private String name;

	private String value;

	private boolean firstIteration;

	public void setName(String propertyName) {
		this.name = propertyName;
	}

	public void setValue(String propertyValue) {
		this.value = propertyValue;
	}

	public int doStartTag() throws JspException {
		TableTag tableTag = (TableTag) findAncestorWithClass(this,
				TableTag.class);

		if (tableTag == null) {
			throw new TagStructureException(getClass(), "setProperty", "table"); //$NON-NLS-1$ //$NON-NLS-2$
		}

		// read body only once
		if (tableTag.isFirstIteration()) {
			this.firstIteration = true;
			// using int to avoid deprecation error in compilation using j2ee
			// 1.3 (EVAL_BODY_TAG)
			return 2;
		}

		this.firstIteration = false;
		return SKIP_BODY;

	}

	public int doEndTag() throws JspException {

		if (this.firstIteration) {
			TableTag tableTag = (TableTag) findAncestorWithClass(this,
					TableTag.class);

			// tableTag can't be null, it has been checked in doStartTag
			if (this.value == null) {
				if (getBodyContent() != null) {
					this.value = getBodyContent().getString();
				}
			}

			tableTag.setAttribute(this.name, this.value);

			this.name = null;
			this.value = null;
		}
		this.name = null;
		this.value = null;
		super.release();
		return EVAL_PAGE;
	}

}